package com.boang.util;

import com.alibaba.druid.pool.DruidDataSource;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/*
  @author: 13813
  @date: 2024/4/3 11:05
*/
public class DBUtil {
    private static Connection connection = null;
    private static DruidDataSource dataSource = null;

    private static ThreadLocal<Connection> local = new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
//            connection = DriverManager.getConnection(properties.getProperty("mysql.url"), properties.getProperty("mysql.username"), properties.getProperty("mysql.password"));
            dataSource = new DruidDataSource();
            //连接url
            dataSource.setUrl(properties.getProperty("mysql.url"));
            //用户名
            dataSource.setUsername(properties.getProperty("mysql.username"));
            //密码
            dataSource.setPassword(properties.getProperty("mysql.password"));
            //初始化连接数
            dataSource.setInitialSize(5);
            //最大连接数
            dataSource.setMaxActive(5);
            //最小连接数
            dataSource.setMinIdle(2);
            //从数据库连接池中获取数据库连接
//            connection = dataSource.getConnection();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConn() throws SQLException, IOException {
        Connection conn = local.get();
        if (conn == null) {
            conn = dataSource.getConnection();
            local.set(conn);
        }
        return conn;
    }

    public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (preparedStatement != null) {
            preparedStatement.close();
        }
        if (connection != null) {
            connection.close();//把连接放回数据库连接池
        }
    }
}
